﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;

using ThousandFunClient.model;
using ThousandFunClient.Util;
using System.Collections;
using System.IO.Ports;
using System.Timers;
using System.Globalization;
using System.Threading;


using System.Net;
using System.Net.Sockets;

namespace virtualHost
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();

            ColumnHeader cZh = new ColumnHeader();//创建一个列
            cZh.Text = "DataReceive";//列名
            ColumnHeader cCh = new ColumnHeader();
            cCh.Text = "DataReply";
            LV_main.Columns.AddRange(new ColumnHeader[] { cZh, cCh });//将这两列加入listView1
        }

        private void button1_Click(object sender, EventArgs e)
        {
             SP_Main.PortName = "com8";

             PortUtil.OpenCOM(SP_Main);

        }


        void CrossThreadCall_Local(string reply)
        {
            LV_main.View = View.Details;//列的显示模式
            ListViewItem lvi = new ListViewItem(new string[] { "dd", reply }, -1);
            LV_main.Items.Add(lvi);
        }
        public delegate void void_d(string reply);

        private int count = 0;
        private int cf = 0;
         
        private void SP_Main_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
             int int_Len = SP_Main.BytesToRead;
             byte[] buf = new byte[int_Len];
             SP_Main.Read(buf, 0, int_Len);
             TFModel tfmodel = DataUtil.parseReceiveint(buf);


            //byte[] bs = convertSendDataBytes("00 08 01 02 8B 00 d0 4a 00 00 4f");
             //byte[] bs = convertSendDataBytes("00 06 01 02 8B 08 05 00 5e");
             //byte[] bs = convertSendDataBytes("00 08 01 02 8B 00 d0 4a 00 00 4f");
            

             //SP_Main.Write(bs, 0, bs.Length);

             //string get = ASCIIEncoding.ASCII.GetString(buf);
             ////MessageBox.Show(get);
             string reply = "";
            string get =tfmodel.ToLogString();
            reply = System.Configuration.ConfigurationSettings.AppSettings[get];

            
            if(get.ToUpper().Equals("00 06 02 01 0B 04 20 00 C7"))
            {
                if (cf == 0)
                {
                    reply = "00 06 01 02 8B 08 07 00 5c";
                    cf = 1;
                }
                else
                {
                    reply = "00 06 01 02 8B 08 00 00 5c";
                    cf = 0;
                }
                
            }
            
                
            if (reply != null)
            {
                 string[] re = reply.Split('|');

                 for (int i = 0; i < re.Length; i++)
                 {
                     byte[] bs = convertSendDataBytes(re[i]);
                     SP_Main.Write(bs, 0, bs.Length);
                     if (re.Length > 1)
                     {
                         Thread.Sleep(100);
                     }
                 }
             }
             //if (reply != null)
             //{
             //    //MessageBox.Show(buf.ToString());

             //    Invoke(new void_d(CrossThreadCall_Local),reply);
             //    SP_Main.Write(reply);
             //}


             //ListViewItem lvi = new ListViewItem(new string[] { buf.ToString(), "23421523" }, -1);
             //LV_main.Items.Add(lvi);
             //LV_main.Columns.Add(buf.ToString());
            

        }

        private void button2_Click(object sender, EventArgs e)
        {
            string reply = System.Configuration.ConfigurationSettings.AppSettings["00 06 02 01 0B 00 40 43 68"];
            LV_main.View = View.Details;//列的显示模式
            ListViewItem lvi = new ListViewItem(new string[] {"dd","狗" }, -1);
            LV_main.Items.Add(lvi);
        }





        public static byte[] convertSendDataBytes(String CMD)
        {
            int[] bs = convertSendDataInt(CMD);
            byte[] bsb = new byte[bs.Length];
            for (int i = 0; i < bs.Length; i++)
            {

                bsb[i] = (byte)bs[i];
            }
            return bsb;
        }
        public static int[] convertSendDataInt(String CMD)
        {
            CMD = CMD.Trim();
            String[] tc = CMD.Split(' ');
            int[] tg = new int[tc.Length];
            for (int i = 0; i < tc.Length; i++)
            {
                tg[i] = Convert.ToInt32(tc[i], 16);
            }


            return tg;
        }


        public static String[] convertSendData(String CMD)
        {
            String[] tc = CMD.Split(' ');
            String[] tg = new String[tc.Length];
            for (int i = 0; i < tc.Length; i++)
            {
                tg[i] = Convert.ToInt32(tc[i], 16).ToString();
            }


            return tg;
        }

        public static String convertSendDataStr(String CMD)
        {
            String[] tg = convertSendData(CMD);
            string ret = "";
            for (int i = 0; i < tg.Length; i++)
            {
                ret = ret + tg[i];
            }

            return ret;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            string mac = txt_mac.Text.Trim().Replace('-', ':');
            string date = txt_date.Text.Trim();
            txt_reg.Text = CryptographyUtil.Encrypt(date + mac);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            byte[] data = new byte[1024];
            Socket newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Console.Write("please input the server ip:");
            string ipadd = "172.16.12.72";
            Console.WriteLine();
            Console.Write("please input the server port:");
            int port = 10111;
            IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ipadd), port);//服务器的IP和端口
            try
            {
                //因为客户端只是用来向特定的服务器发送信息，所以不需要绑定本机的IP和端口。不需要监听。
                newclient.Connect(ie);
            }
            catch (SocketException ex)
            {
                Console.WriteLine("unable to connect to server");
                Console.WriteLine(ex.ToString());
                return;
            }
            int recv = newclient.Receive(data);
            string stringdata = Encoding.ASCII.GetString(data, 0, recv);
            Console.WriteLine(stringdata);
            while (true)
            {
                string input = "jiaquanzhen";
                if (input == "exit")
                    break;
                newclient.Send(Encoding.ASCII.GetBytes(input));
                data = new byte[1024];
                recv = newclient.Receive(data);
                stringdata = Encoding.ASCII.GetString(data, 0, recv);
                Console.WriteLine(stringdata);
            }
            Console.WriteLine("disconnect from sercer");
            newclient.Shutdown(SocketShutdown.Both);
            newclient.Close();
 
        }

        private void button5_Click(object sender, EventArgs e)
        {
            byte[] data = new byte[1024];//定义一个数组用来做数据的缓冲区
            string input, stringData;
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            string welcome = "Hello,are you there?";
            data = Encoding.ASCII.GetBytes(welcome);
            server.SendTo(data, data.Length, SocketFlags.None, ipep);//将数据发送到指定的终结点

            IPEndPoint ipsender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = (EndPoint)ipsender;
            data = new byte[1024];
            int recv = server.ReceiveFrom(data, ref Remote);//接受来自服务器的数据

            Console.WriteLine("Message received from{0}:", Remote.ToString());
            Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
            while (true)//读取数据
            {
                input = Console.ReadLine();//从键盘读取数据
                if (input == "text")//结束标记
                {
                    break;
                }
                server.SendTo(Encoding.ASCII.GetBytes(input), Remote);//将数据发送到指定的终结点Remote
                data = new byte[1024];
                recv = server.ReceiveFrom(data, ref Remote);//从Remote接受数据
                stringData = Encoding.ASCII.GetString(data, 0, recv);
                Console.WriteLine(stringData);
            }
            Console.WriteLine("Stopping client");
            server.Close();
 
        }



        private IPEndPoint ServerInfo;
        private Socket ClientSocket;
        //信息接收缓存
        private Byte[] MsgBuffer;
        //信息发送存储
        private Byte[] MsgSend;

        private void CmdEnter_Click(object sender, EventArgs e)
        {
            //定义一个IPV4，TCP模式的Socket
            ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            MsgBuffer = new Byte[65535];
            MsgSend = new Byte[65535];
            //允许子线程刷新数据
            CheckForIllegalCrossThreadCalls = false;

            //服务端IP和端口信息设定,这里的IP可以是127.0.0.1，可以是本机局域网IP，也可以是本机网络IP
            ServerInfo = new IPEndPoint(IPAddress.Parse("172.16.12.72"), 6575);

            try
            {
                //客户端连接服务端指定IP端口，Sockket
                ClientSocket.Connect(ServerInfo);
                //将用户登录信息发送至服务器，由此可以让其他客户端获知
                ClientSocket.Send(Encoding.Unicode.GetBytes("用户： " + this.UserName.Text + " 进入系统！\n"));
                //开始从连接的Socket异步读取数据。接收来自服务器，其他客户端转发来的信息
                //AsyncCallback引用在异步操作完成时调用的回调方法
                ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), null);

                this.CmdSend.Enabled = true;
                this.CmdEnter.Enabled = false;
                this.CmdExit.Enabled = true;
            }
            catch
            {
                MessageBox.Show("登录服务器失败，请确认服务器是否正常工作！");
            }
        }

        private void ReceiveCallBack(IAsyncResult AR)
        {
            try
            {
                //结束挂起的异步读取，返回接收到的字节数。 AR，它存储此异步操作的状态信息以及所有用户定义数据
                int REnd = ClientSocket.EndReceive(AR);

                lock (this.RecieveMsg)
                {
                    this.RecieveMsg.AppendText(Encoding.Unicode.GetString(MsgBuffer, 0, REnd));
                }
                ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);

            }
            catch
            {
                MessageBox.Show("已经与服务器断开连接！");
                this.Close();
            }

        }
        //点击发送之后没有直接添加到信息列表中，而是传到服务器，由服务器转发给每个客户端
        private void CmdSend_Click(object sender, EventArgs e)
        {

            MsgSend = Encoding.Unicode.GetBytes(this.UserName.Text + "说：\n" + this.SendMsg.Text + "\n");
            if (ClientSocket.Connected)
            {
                //将数据发送到连接的 System.Net.Sockets.Socket。
                ClientSocket.Send(MsgSend);
                this.SendMsg.Text = "";

            }
            else
            {
                MessageBox.Show("当前与服务器断开连接，无法发送信息！");
            }
        }

        private void CmdExit_Click(object sender, EventArgs e)
        {
            if (ClientSocket.Connected)
            {
                ClientSocket.Send(Encoding.Unicode.GetBytes(this.UserName.Text + "离开了房间！\n"));
                //禁用发送和接受
                ClientSocket.Shutdown(SocketShutdown.Both);
                //关闭套接字，不允许重用
                ClientSocket.Disconnect(false);
            }
            ClientSocket.Close();

            this.CmdSend.Enabled = false;
            this.CmdEnter.Enabled = true;
            this.CmdExit.Enabled = false;
        }

        private void RecieveMsg_TextChanged(object sender, EventArgs e)
        {
            this.RecieveMsg.ScrollToCaret();
        }

        private void SendMsg_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyValue == 13)
            {
                e.Handled = true;
                this.CmdSend_Click(this, null);
            }
        }

    }
}
